package com.founder.creater;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import com.founder.creater.domain.DpubInfo;
import com.founder.creater.utils.DigestUtils;
import com.founder.creater.utils.IdGenertor;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

/**
 * 版权所有：北京北大方正电子有限公司</br>
 * 
 * Creater </br>
 * 
 * @author zhou.wenkai ,Created on 2016-4-1 17:29:25</br>
 * @Description Major Function：<b>文件操作工具类</b> </br>
 * 
 * 注:如果您修改了本类请填写以下内容作为记录，如非本人操作劳烦通知，谢谢！！！</br>
 * @author mender，Modified Date Modify Content:
 */
public class Creater implements ActionListener {
	
	private JFrame frame = new JFrame("DPUB资源索引生成工具");
	private JTextArea area = new JTextArea(8, 10);
	private JButton open = new JButton("选择目录");
	private JButton save = new JButton("开始运行");
	private JLabel label = new JLabel("您没有选择文件目录");
	private JPanel butPanel = new JPanel();
	
	/** 选择的文件目录 */
	private String chooserFilePath;
	
	public Creater() {
		super();
		initView();
	}
	
	private void initView() {
		butPanel.add(open);
		butPanel.add(save);
		open.addActionListener(this);
		save.addActionListener(this);
		frame.setLayout(new BorderLayout(3, 3));
		frame.add(label, BorderLayout.NORTH);
		frame.add(butPanel, BorderLayout.SOUTH);
		frame.add(new JScrollPane(area), BorderLayout.CENTER);
		frame.setVisible(true);
		frame.setLocation(400, 300);
		frame.setSize(400, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		initDesc();
	}

	private void initDesc() {
		this.area.setText("");// 将文字区域的内容清空
		this.area.append("说明：\n");
		this.area.append("用于便捷生成dpub资源索引文件\n\n");
		this.area.append("使用步骤：\n");
		this.area.append("1.选择DPUB资源目录\n");
		this.area.append("2.生成资源索引\n");
		this.area.append("\n版权所有：北京北大方正电子有限公司\n");
		this.area.append("\n版本号：1.0.0\n");
		this.area.append("时间：2016-04-01\n");
		this.area.append("zhouwk@founder.com.cn\n");
	}
	
	public void actionPerformed(ActionEvent e) {
		File file = null;	// 接收文件
		int result = 0; 	// 接收操作状态
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);// 只能选择目录
		if (e.getSource() == this.open) {
			this.area.setText("");	// 将文字区域的内容清空
			
			fileChooser.setApproveButtonText("确定");
			fileChooser.setDialogTitle("选择目录");
			result = fileChooser.showOpenDialog(this.frame);
			if (result == JFileChooser.APPROVE_OPTION) { // 选择的是确定
				file = fileChooser.getSelectedFile();
				label.setText("选择的目录是：" + file.getAbsolutePath());
			} else if (result == JFileChooser.CANCEL_OPTION) {
				label.setText("没有选择任何目录！");
			} else {
				label.setText("操作错误！");
			}
			if (file != null) {
				chooserFilePath = file.getAbsolutePath();
			}
		}
		if (e.getSource() == this.save) {
			if(null == chooserFilePath) {
				label.setText("操作错误,请您选择目录后重试！");
			} else {
				ergodicAllFiles(new File(chooserFilePath));
			}
		}
	}

	/**
	 * 遍历接收一个文件路径
	 * 
	 * @param root
	 * @return void:
	 * @version 1.0 
	 * @date 2015-9-2
	 * @Author zhou.wenkai
	 */
	public void ergodicAllFiles(File root) {
		List<DpubInfo> list = new ArrayList<DpubInfo>();
		File files[] = root.listFiles();
		if (files != null) {
			for (File f : files) {
				if (!f.isDirectory()) {
					filterFile(f, list);
				}
			}
		}
		String json = new Gson().toJson(list);
		json = jsonFormatter(json);
		saveAsFileWriter(json, chooserFilePath + "/defaultdpub.json");
	}
	
	/**
	 * 筛选文件
	 * 
	 * @param f
	 * @return void:
	 * @version 1.0 
	 * @param list 
	 * @param list 
	 */
	private void filterFile(final File f, List<DpubInfo> list) {
		final String filePath = f.getAbsolutePath().replace('\\', '/');
		boolean isDpub = isDpub(filePath);
		if (isDpub) {
			String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
			DpubInfo dpubInfo = new DpubInfo();
			dpubInfo.originalName = fileName;
			String digital = getDigitalAndLetter(fileName);
			dpubInfo.name = digital.equals("") ? IdGenertor.generateGUID() + ".dpub" : digital + ".dpub";
			boolean success = f.renameTo(new File(chooserFilePath + "/" + dpubInfo.name));   //改名
			int i = 0;
			while(!success) {
				dpubInfo.name = digital + i + ".dpub";
				success = f.renameTo(new File(chooserFilePath + "/" + dpubInfo.name));   //改名
				i++;
			}
			dpubInfo.sha1 = DigestUtils.getFileSha1(new File(chooserFilePath + "/" + dpubInfo.name));
			list.add(dpubInfo);
			area.append(filePath);
            area.append("\n");
			area.append(dpubInfo.name);
            area.append("\n");
            area.setCaretPosition(area.getText().length());
		}
	}
	
	public String getDigitalAndLetter(String str) {
		String result = "";
		if (str != null && !"".equals(str)) {
			for (int i = 0; i < str.length(); i++) {
				if (str.charAt(i) >= 48 && str.charAt(i) <= 57 ||
						str.charAt(i) >= 65 && str.charAt(i) <= 90) {
					result += str.charAt(i);
				} else {
//					break;
				}
			}
		}
		return result;
	}
	
	/**
     * 判断是否为要修改文件
     * @param str
     * @return
     */
	public boolean isDpub(String str) {
		// xxx.html
		return str.endsWith(".dpub");
	}

	/**
	 * 格式化JSON
	 * 
	 * @param json
	 * @return
	 * @version 1.0 
	 * @date 2016-4-5
	 * @Author zwenkai
	 */
	public static String jsonFormatter(String json) {
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		JsonParser jp = new JsonParser();
		JsonElement je = jp.parse(json);
		String prettyJsonString = gson.toJson(je);
		return prettyJsonString;
	}

	/**
	 * 保存字符串到文件
	 * 
	 * @param content
	 * @param path
	 * @return void:
	 * @version 1.0 
	 * @date 2016-4-5
	 * @Author zwenkai
	 */
	private void saveAsFileWriter(String content, String path) {
		FileWriter fwriter = null;
		try {
			fwriter = new FileWriter(path);
			fwriter.write(content);
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				fwriter.flush();
				fwriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
